<template>
  <div class="app-container">
    <el-divider content-position="center">编号规则配置</el-divider>
    <el-row>
      <el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="120px" :loading="loading">
        <el-form-item label="编号规则名称" prop="ruleName">
          {{ form.ruleName }}
        </el-form-item>
        <el-form-item label="分隔符字典" prop="fgf" class="remove-bottom">
          <el-select clearable v-model="form.fgf" placeholder="请选择分隔符字典" @change="fgfChange(form.fgf)"
            style="margin-bottom: 5px;">
            <el-option v-for="dict in dict.type.fgf" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" :loading="buttonLoading" type="primary" @click="submitForm"
            style="margin-left: 10px;">保
            存</el-button>
        </el-form-item>
        <el-table border stripe :data="form.tableData">
          <el-table-column label="序号" align="center" width="80">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="pType" label="规则类型" align="center" :show-overflow-tooltip="true">
            <template #header>
              <el-tooltip class="item" effect="dark" :content="'这是必填项'" placement="top">
                <span>
                  <span style="color: red;">*</span>
                  规则类型
                </span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-form-item :prop="'tableData[' + scope.$index + '].pType'" :rules="rules.pType" class="remove-bottom">
                <el-select @change="pTypeChange(scope.row)" clearable v-model="scope.row.pType" placeholder="请选择规则类型"
                  size="small">
                  <el-option v-for="dict in dict.type.sycs_rule_p" :key="dict.value" :label="dict.label"
                    :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="sl" label="示例" align="center" :show-overflow-tooltip="true" />
          <el-table-column prop="pContent" label="规则内容" align="center" :show-overflow-tooltip="true">
            <template #header>
              <el-tooltip class="item" effect="dark" :content="'这是必填项'" placement="top">
                <span>
                  <span style="color: red;">*</span>
                  规则内容
                </span>
              </el-tooltip>
            </template>
            <template #default="scope">
              <el-form-item :prop="'tableData[' + scope.$index + '].pContent'" :rules="rules.pContent"
                class="remove-bottom">
                <el-input clearable v-model="scope.row.pContent" size="small" placeholder="请输入内容"
                  @blur="createRes(scope.row)" v-if="scope.row.pType == '35' || scope.row.pType == '00'"></el-input>
                <el-input clearable v-model="scope.row.pContent" size="small" placeholder="请输入内容"
                  @blur="createRes(scope.row)" :disabled="true" v-else></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="180">
            <template #default="scope">
              <el-popconfirm title="确定删除该条数据吗？" @confirm='dataDel(scope.row, scope.$index)'>
                <!-- <el-link slot="reference" type="primary" style="margin-right: 20px;">删除</el-link> -->
                <el-button slot="reference" size="mini" type="text" style="margin-right: 10px;">删除</el-button>
              </el-popconfirm>
              <el-button size="mini" type="text" @click="dataAdd(scope.row)"
                :disabled="form.tableData.length > 5">添加</el-button>
              <el-button size="mini" type="text" @click="moveupOrmovedown(scope.row, scope.$index, 'up')"
                :disabled="!(scope.$index != 0)">上移</el-button>
              <el-button size="mini" type="text" @click="moveupOrmovedown(scope.row, scope.$index, 'down')"
                :disabled="scope.$index == (form.tableData.length - 1)">下移</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

    </el-row>
    <el-divider content-position="center">示例信息</el-divider>
    <el-row>
      <el-table border stripe :data="slList">
        <el-table-column label="编号规则名称" align="center" prop="bhName" :show-overflow-tooltip="true" />
        <el-table-column label="效果预览" align="center" prop="bhValue" :show-overflow-tooltip="true" />
      </el-table>
    </el-row>

  </div>
</template>

<script>
import { listBsRule, getBsRule, delBsRule, addBsRule, updateBsRule, getRule, deptTree } from "@/api/sycs/bsRule";
import { mapGetters } from "vuex";

export default {
  name: "BsRule",
  dicts: ['sycs_rule_p', 'fgf'],
  data () {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 编号规则设置表格数据
      bsRuleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        syTypeId: undefined,
        ruleName: undefined,
        fgf: undefined,
        p1Type: undefined,
        p1Content: undefined,
        p2Type: undefined,
        p2Content: undefined,
        p3Type: undefined,
        p3Content: undefined,
        p4Type: undefined,
        p4Content: undefined,
        p5Type: undefined,
        p5Content: undefined,
        p6Type: undefined,
        p6Content: undefined,
      },
      // 表单参数
      form: {
        ruleName: '样品编号 / 记录编号 / 报告编号',
        tableData: [
          {
            date: Date.now(),
            sl: '',
            pType: undefined,
            pContent: undefined,
          },
        ],
      },
      // 表单校验
      rules: {
        fgf: [
          { required: true, message: "分隔符字典不能为空", trigger: "change" }
        ],
        pType: [
          { required: true, message: "规则类型不能为空", trigger: "change" }
        ],
        pContent: [
          { required: true, message: "规则内容不能为空", trigger: "blur" }
        ],
      },
      syTypeName: undefined,
      options: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 当前树节点
      currentNode: {},
      oneShow: false, // 点击树显示子表
      slList: [
        {
          bhName: '样品编号',
          bhValue: undefined
        },
        {
          bhName: '记录编号',
          bhValue: undefined
        },
        {
          bhName: '报告编号',
          bhValue: undefined
        },
      ],
      res: undefined, // 示例值
    };
  },
  created () {
    this.getRule();
  },
  computed: {
    ...mapGetters([
      'deptId',
    ])
  },
  watch: {
    deptId (newValue, oldValue) {
      this.deptId = newValue;
      console.log('-----------deptId-----------', this.deptId);
      this.getRule();
    }
  },
  methods: {
    selectDept () {
      let flag = true
      if (!this.deptId) {
        this.$alert('', '请选择试验室', {
          confirmButtonText: '确定',
          type: 'warning',
          center: true
        });
        flag = false;
        this.$refs.form.resetFields()
      } else {
        flag = true;
      }
      return flag;
    },
    // 根据试验类型id查询编号规则
    getRule () {
      if (this.selectDept()) {
        const params = {
          // syTypeId: this.currentNode.id,
          deptId: this.deptId
        }
        getRule(params).then(response => {
          if (!!response && !!response.data) {
            this.form = response.data
            const data = response.data
            const tableData = []
            if ((!!data.p1Type && !!data.p1Content) && (!data.p2Type && !data.p2Content)) {
              const obj = {
                date: Date.now(),
                sl: '',
                pType: data.p1Type,
                pContent: data.p1Content,
              }
              this.$set(obj, 'sl', this.createSl(obj.pType))
              tableData.push(obj)
            }
            else if ((!!data.p1Type && !!data.p1Content) && (!!data.p2Type && !!data.p2Content) && (!data.p3Type && !data.p3Content)) {
              const obj = {
                date: Date.now(),
                sl: '',
                pType: data.p1Type,
                pContent: data.p1Content,
              }
              this.$set(obj, 'sl', this.createSl(obj.pType))
              const obj2 = {
                date: Date.now(),
                sl: '',
                pType: data.p2Type,
                pContent: data.p2Content,
              }
              this.$set(obj2, 'sl', this.createSl(obj2.pType))
              tableData.push(obj)
              tableData.push(obj2)
            }
            else if ((!!data.p1Type && !!data.p1Content) && (!!data.p2Type && !!data.p2Content) && (!!data.p3Type && !!data.p3Content) && (!data.p4Type && !data.p4Content)) {
              const obj = {
                date: Date.now(),
                sl: '',
                pType: data.p1Type,
                pContent: data.p1Content,
              }
              this.$set(obj, 'sl', this.createSl(obj.pType))
              const obj2 = {
                date: Date.now(),
                sl: '',
                pType: data.p2Type,
                pContent: data.p2Content,
              }
              this.$set(obj2, 'sl', this.createSl(obj2.pType))
              const obj3 = {
                date: Date.now(),
                sl: '',
                pType: data.p3Type,
                pContent: data.p3Content,
              }
              this.$set(obj3, 'sl', this.createSl(obj3.pType))
              tableData.push(obj)
              tableData.push(obj2)
              tableData.push(obj3)
            }
            else if ((!!data.p1Type && !!data.p1Content) && (!!data.p2Type && !!data.p2Content) && (!!data.p3Type && !!data.p3Content) && (!!data.p4Type && !!data.p4Content)
              && (!data.p5Type && !data.p5Content)) {
              const obj = {
                date: Date.now(),
                sl: '',
                pType: data.p1Type,
                pContent: data.p1Content,
              }
              this.$set(obj, 'sl', this.createSl(obj.pType))
              const obj2 = {
                date: Date.now(),
                sl: '',
                pType: data.p2Type,
                pContent: data.p2Content,
              }
              this.$set(obj2, 'sl', this.createSl(obj2.pType))
              const obj3 = {
                date: Date.now(),
                sl: '',
                pType: data.p3Type,
                pContent: data.p3Content,
              }
              this.$set(obj3, 'sl', this.createSl(obj3.pType))
              const obj4 = {
                date: Date.now(),
                sl: '',
                pType: data.p4Type,
                pContent: data.p4Content,
              }
              this.$set(obj4, 'sl', this.createSl(obj4.pType))
              tableData.push(obj)
              tableData.push(obj2)
              tableData.push(obj3)
              tableData.push(obj4)
            }
            else if ((!!data.p1Type && !!data.p1Content) && (!!data.p2Type && !!data.p2Content) && (!!data.p3Type && !!data.p3Content) && (!!data.p4Type && !!data.p4Content)
              && (!!data.p5Type && !!data.p5Content) && (!data.p6Type && !data.p6Content)) {
              const obj = {
                date: Date.now(),
                sl: '',
                pType: data.p1Type,
                pContent: data.p1Content,
              }
              this.$set(obj, 'sl', this.createSl(obj.pType))
              const obj2 = {
                date: Date.now(),
                sl: '',
                pType: data.p2Type,
                pContent: data.p2Content,
              }
              this.$set(obj2, 'sl', this.createSl(obj2.pType))
              const obj3 = {
                date: Date.now(),
                sl: '',
                pType: data.p3Type,
                pContent: data.p3Content,
              }
              this.$set(obj3, 'sl', this.createSl(obj3.pType))
              const obj4 = {
                date: Date.now(),
                sl: '',
                pType: data.p4Type,
                pContent: data.p4Content,
              }
              this.$set(obj4, 'sl', this.createSl(obj4.pType))
              const obj5 = {
                date: Date.now(),
                sl: '',
                pType: data.p5Type,
                pContent: data.p5Content,
              }
              this.$set(obj5, 'sl', this.createSl(obj5.pType))
              tableData.push(obj)
              tableData.push(obj2)
              tableData.push(obj3)
              tableData.push(obj4)
              tableData.push(obj5)
            }
            else if ((!!data.p1Type && !!data.p1Content) && (!!data.p2Type && !!data.p2Content) && (!!data.p3Type && !!data.p3Content) && (!!data.p4Type && !!data.p4Content)
              && (!!data.p5Type && !!data.p5Content) && (!!data.p6Type && !!data.p6Content)) {
              const obj = {
                date: Date.now(),
                sl: '',
                pType: data.p1Type,
                pContent: data.p1Content,
              }
              this.$set(obj, 'sl', this.createSl(obj.pType))
              const obj2 = {
                date: Date.now(),
                sl: '',
                pType: data.p2Type,
                pContent: data.p2Content,
              }
              this.$set(obj2, 'sl', this.createSl(obj2.pType))
              const obj3 = {
                date: Date.now(),
                sl: '',
                pType: data.p3Type,
                pContent: data.p3Content,
              }
              this.$set(obj3, 'sl', this.createSl(obj3.pType))
              const obj4 = {
                date: Date.now(),
                sl: '',
                pType: data.p4Type,
                pContent: data.p4Content,
              }
              this.$set(obj4, 'sl', this.createSl(obj4.pType))
              const obj5 = {
                date: Date.now(),
                sl: '',
                pType: data.p5Type,
                pContent: data.p5Content,
              }
              this.$set(obj5, 'sl', this.createSl(obj5.pType))
              const obj6 = {
                date: Date.now(),
                sl: '',
                pType: data.p6Type,
                pContent: data.p6Content,
              }
              this.$set(obj6, 'sl', this.createSl(obj6.pType))
              tableData.push(obj)
              tableData.push(obj2)
              tableData.push(obj3)
              tableData.push(obj4)
              tableData.push(obj5)
              tableData.push(obj6)
            }
            this.$set(this.form, 'tableData', tableData)
            this.$nextTick(() => {
              this.$refs.form.clearValidate();
            });
            this.createRes()
          } else {
            this.form = {
              ruleName: '样品编号 / 记录编号 / 报告编号',
              tableData: [
                {
                  date: Date.now(),
                  sl: '',
                  pType: undefined,
                  pContent: undefined,
                },
              ],
            };
            this.slList = [
              {
                bhName: '样品编号',
                bhValue: undefined
              },
              {
                bhName: '记录编号',
                bhValue: undefined
              },
              {
                bhName: '报告编号',
                bhValue: undefined
              },
            ];
            this.$nextTick(() => {
              this.$refs.form.clearValidate();
            });
          }
          this.loading = false;
        })
      } else {
        return;
      }
    },
    /** 提交按钮 */
    submitForm () {
      if (this.selectDept()) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // 拼接参数
            // let deptId= this.deptId?this.deptId:this.$store.state.dept.deptId;
            this.$set(this.form, 'deptId', this.deptId);
            // this.$set(this.form, 'syTypeId', this.currentNode.id);
            for (let i = 0; i < this.form.tableData.length; i++) {
              this.$set(this.form, 'p' + (i + 1) + 'Type', this.form.tableData[i].pType)
              this.$set(this.form, 'p' + (i + 1) + 'Content', this.form.tableData[i].pContent)
            }
            this.buttonLoading = true;
            if (this.form.ruleId != null) {
              updateBsRule(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addBsRule(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      } else {
        return;
      }
    },
    // 删除一行
    dataDel (row, index) {
      if (this.selectDept()) {
        if (!!this.form.tableData && this.form.tableData.length > 1) {
          this.form.tableData.splice(index, 1)
        } else {
          this.$message({
            message: '无法删除当前行',
            type: 'error',
            offset: 150
          });
        }
        this.createRes(row)
      } else {
        return;
      }
    },
    // 添加一行
    dataAdd (row) {
      if (this.selectDept()) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let obj = {
              date: Date.now(),
              pType: undefined,
              pContent: undefined
            }
            this.form.tableData.push(obj)
            this.createRes(row)
          } else {
            return false;
          }
        });
      } else {
        return;
      }
    },
    moveupOrmovedown (row, index, type) {
      if (this.selectDept()) {
        let arr = this.form.tableData
        let findIndex = this.form.tableData.findIndex(
          (item) => item.date === row.date
        )
        index = findIndex > this.queryParams.pageSize - 1 ? findIndex : index
        type === 'up'
          ? arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]))
          : arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]))
        this.createRes(row)
      } else {
        return;
      }
    },
    // 改变下拉选择框的值时,判断后将值添加到示例中
    pTypeChange (row) {
      if (this.selectDept()) {
        let pType = row.pType;
        let sl;
        switch (pType) {
          case '00':
            sl = 'TG';
            if (!!row.pContent) {
              row.pContent = undefined
            }
            break;
          case '0100':
            sl = new Date().getFullYear();
            row.pContent = sl
            break;
          case '0101':
            sl = new Date().getFullYear() + '' + ((new Date().getMonth() + 1) > 10 ? (new Date().getMonth() + 1) : ('0' + (new Date().getMonth() + 1)));
            row.pContent = sl
            break;
          case '0102':
            sl = ((new Date().getMonth() + 1) > 10 ? (new Date().getMonth() + 1) : ('0' + (new Date().getMonth() + 1))) + '' + new Date().getFullYear();
            row.pContent = sl
            break;
          case '0200':
            sl = '0001';
            row.pContent = sl
            break;
          case '0201':
            sl = '001';
            row.pContent = sl
            break;
          case '33':
            sl = 'YP/JL/BG';
            row.pContent = 'YP/JL/BG';
            break;
          case '35':
            sl = 'JWZD1';
            if (!!row.pContent) {
              row.pContent = undefined
            }
            break;
          case '36':
            sl = 'TG';
            row.pContent = '试验标识';
            break;
          default:
            sl = undefined;
            if (!!row.pContent) {
              row.pContent = undefined
            }
        }
        let i = this.form.tableData.findIndex(item => {
          if (item.date === row.date) {
            return true
          }
        })
        this.$set(this.form.tableData[i], 'sl', sl)
        this.createRes(row)
      } else {
        return;
      }
    },
    createSl (pType) {
      let sl;
      switch (pType) {
        case '00':
          sl = 'TG';
          break;
        case '0100':
          sl = new Date().getFullYear();
          break;
        case '0101':
          sl = new Date().getFullYear() + '' + ((new Date().getMonth() + 1) > 10 ? (new Date().getMonth() + 1) : ('0' + (new Date().getMonth() + 1)));
          break;
        case '0102':
          sl = ((new Date().getMonth() + 1) > 10 ? (new Date().getMonth() + 1) : ('0' + (new Date().getMonth() + 1))) + '' + new Date().getFullYear();
          break;
        case '0200':
          sl = '0001';
          break;
        case '0201':
          sl = '001';
          break;
        case '33':
          sl = 'YP/JL/BG';
          break;
        case '35':
          sl = 'JWZD1';
          break;
        case '36':
          sl = 'TG';
          break;
        default:
          sl = undefined;
      }
      return sl;
    },
    createRes (row) {
      let fgfLabel = '';
      // 获取分隔符
      for (let i = 0; i < this.dict.type.fgf.length; i++) {
        const dict = this.dict.type.fgf[i];
        if (dict.value == this.form.fgf) {
          fgfLabel = dict.label;
          break;
        } else {
          fgfLabel = '';
        }
      }
      this.res = '';
      for (let i = 0; i < this.form.tableData.length; i++) {
        if (i < this.form.tableData.length - 1) {
          if (!!this.form.tableData[i].pContent) {
            this.res += this.form.tableData[i].pContent + fgfLabel
          }
        } else {
          if (!!this.form.tableData[i].pContent) {
            this.res += this.form.tableData[i].pContent
          }
        }
      }
      this.res = this.res.replace('试验标识', 'TG')
      this.slList[0].bhValue = this.res.replace('YP/JL/BG', 'YP')
      this.slList[1].bhValue = this.res.replace('YP/JL/BG', 'JL')
      this.slList[2].bhValue = this.res.replace('YP/JL/BG', 'BG')
    },
    fgfChange (fgf) {
      if (this.selectDept()) {
        this.createRes()
      } else {
        return;
      }
    }

  }
};
</script>
<style lang="scss" scoped>
@import '~@/assets/styles/demo.scss';

.el-form-item {
  margin-bottom: 0 !important;
}
</style>
